package com.taoyige.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.adapter.ListAddressAdapter;
import com.taoyige.bean.Address;
import com.taoyige.bean.AddressList;
import com.taoyige.bean.Order;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.LoadingDialog;

/**
 * 用户地址管理
 * @author zhuxun
 * @version 1.0
 * @date 2014-11-25 上午9:56:40
 */
public class AddressDetailActivity extends BaseActivity {
	
	private AppContext appContext;
	private Handler handler;
	private Handler handlerA;
	private LoadingDialog loading;
	
	private ImageButton returnBack;
	private ImageButton homePage;
	private TextView userHeadText;
	private Button button;
	private ListView locationListView;
	private ListAddressAdapter listAddressAdapter;
	private String userId="0";
	
	private InputStream inputStream;
	private List<Address> addresslistTown;
	
	private Order order;
	private int status;
	private int dosomething;
	private Boolean locationB;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_main);
		appContext=(AppContext) getApplication();
		userId=appContext.getLoginUid();
		this.initView();
		this.initData();
	}
	
	private void initView(){
		order=(Order) getIntent().getSerializableExtra("order");
		status=getIntent().getIntExtra("status", 0);
		dosomething = getIntent().getIntExtra("dosomething", 0);
		returnBack=(ImageButton)findViewById(R.id.user_hear_return_back);
		homePage=(ImageButton)findViewById(R.id.user_hear_homePage);
		userHeadText=(TextView)findViewById(R.id.user_hear_text);
		userHeadText.setText("我的收货地址");
		
		button=(Button)findViewById(R.id.location_main_button);
		locationListView=(ListView)findViewById(R.id.location_main_detail_listview);
		
		inputStream=this.getResources().openRawResource(R.raw.locations);  
	}
	
	private void initData() {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 && msg.obj != null) {
					addresslistTown = (List<Address>) msg.obj;
					listAddressAdapter = new ListAddressAdapter(AddressDetailActivity.this,AddressDetailActivity.this, addresslistTown,R.layout.user_address,order,userId,status);
					locationListView.setAdapter(listAddressAdapter);
				}else if(msg.what==2){
					locationB=true;
				}else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(AddressDetailActivity.this);
				}
			}
		};
		if(status==1){
			returnBack.setOnClickListener(homeListener);
		}else{
			returnBack.setOnClickListener(userListener);
		}
		if(dosomething==1){
			UIHelper.ToastMessage(AddressDetailActivity.this, "地址修改成功");
		}else if(dosomething==2){
			UIHelper.ToastMessage(AddressDetailActivity.this, "新增地址成功");
		}
		homePage.setOnClickListener(homeListener);
		button.setOnClickListener(addAddressListener);
		this.loadUserInfomationThread();
	}
	
	private void loadUserInfomationThread() {
		loading = new LoadingDialog(this);
		loading.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					AddressList addressList= ((AppContext) getApplication()).getAddrList(userId);
					List<Address> address = addressList.getList();
					msg.what = 1;
					msg.obj = address;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
		if(addressIdList.get(0).equals("-1")){
			setLocationJsonObject();
		}else{
			locationB=true;
		}
	}
	
	public void setLocationJsonObject(){
		new Thread() {
			Message msg = new Message();
			public void run() {
				try {
					JSONObject jsonOject= ((AppContext) getApplication()).getLocation(inputStream);
					addressIdList = new ArrayList<String>();
					addressIdList.add("1");addressIdList.add("1");addressIdList.add("1");addressIdList.add("1");
					addressNameList = new ArrayList<String>();
					addressNameList.add("1");addressNameList.add("1");addressNameList.add("1");addressNameList.add("1");
					addressClassList = new ArrayList<String>();
					addressClassList.add("1");addressClassList.add("1");addressClassList.add("1");addressClassList.add("1");
					Iterator it = jsonOject.keys();
					while(it.hasNext()){
						String one=it.next().toString();
						if(one.equals("110000")){
							addressIdList.set(0, one);
							try {
								JSONArray jsonArray = new JSONArray(jsonOject.getString(one));
								addressNameList.set(0,jsonArray.getString(0));
								addressClassList.set(0,jsonArray.getString(1));
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else if(one.equals("120000")){
							addressIdList.set(1, one);
							try {
								JSONArray jsonArray = new JSONArray(jsonOject.getString(one));
								addressNameList.set(1,jsonArray.getString(0));
								addressClassList.set(1,jsonArray.getString(1));
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else if(one.equals("310000")){
							addressIdList.set(2, one);
							try {
								JSONArray jsonArray = new JSONArray(jsonOject.getString(one));
								addressNameList.set(2,jsonArray.getString(0));
								addressClassList.set(2,jsonArray.getString(1));
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else if(one.equals("500000")){
							addressIdList.set(3, one);
							try {
								JSONArray jsonArray = new JSONArray(jsonOject.getString(one));
								addressNameList.set(3,jsonArray.getString(0));
								addressClassList.set(3,jsonArray.getString(1));
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}else{
							addressIdList.add(one);
							try {
								JSONArray jsonArray = new JSONArray(jsonOject.getString(one));
								addressNameList.add(jsonArray.getString(0));
								addressClassList.add(jsonArray.getString(1));
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						msg.what = 2;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();	
	}
	
	public View.OnClickListener buyNowListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showBuyNow(v.getContext(),order);
		}
	};
	
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(status==1){
				UIHelper.showHomePage(AddressDetailActivity.this);
			}else{
				UIHelper.showUser(AddressDetailActivity.this);
			}
		} 
		return flag;
	}
	
	public View.OnClickListener addAddressListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(!locationB){
				handler = new Handler() {
					public void handleMessage(Message msg) {
						if(msg.what==2){
							loading.dismiss();
							Intent intent = new Intent(AddressDetailActivity.this, AddAddressActivity.class);
							Address address = new Address();
							address.setId("-1");address.setUserID(userId);
							intent.putExtra("address", address);
							intent.putExtra("order", order);
							intent.putExtra("status", status);
							AddressDetailActivity.this.startActivity(intent);
							finish();
						}else if (msg.obj != null) {
							((AppException) msg.obj).makeToast(AddressDetailActivity.this);
						}
					}
				};
				loading = new LoadingDialog(AddressDetailActivity.this);
				loading.show();
				setLocationJsonObject();	
			}else{
				Intent intent = new Intent(AddressDetailActivity.this, AddAddressActivity.class);
				Address address = new Address();
				address.setId("-1");address.setUserID(userId);
				intent.putExtra("address", address);
				intent.putExtra("order", order);
				intent.putExtra("status", status);
				AddressDetailActivity.this.startActivity(intent);
			}
		}
	};
	
	public View.OnClickListener userListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showUser(v.getContext());
		}
	};
	
	public View.OnClickListener homeListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			UIHelper.showHomePage(v.getContext());
		}
	};
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
